home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 2.iso / nt / emacssrc.zip / EMACSSRC.TAR / emacs-19.17 / src / callproc.c < prev    next >
C/C++ Source or Header  |  1993-11-22  |  27KB  |  934 lines

  1. /* Synchronous subprocess invocation for GNU Emacs.
  2.    Copyright (C) 1985, 1986, 1987, 1988, 1993 Free Software Foundation, Inc.
  3.  
  4. This file is part of GNU Emacs.
  5.  
  6. GNU Emacs is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 1, or (at your option)
  9. any later version.
  10.  
  11. GNU Emacs is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU Emacs; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20.  
  21. #include <signal.h>
  22. #include <errno.h>
  23.  
  24. #include "config.h"
  25.  
  26. #ifdef STDC_HEADERS
  27. #include <stdlib.h>
  28. #include <stdio.h>
  29. #include <io.h>
  30. #else
  31. extern int errno;
  32. #ifndef VMS
  33. extern char *sys_errlist[];
  34. #endif
  35. #endif
  36.  
  37. /* Define SIGCHLD as an alias for SIGCLD.  */
  38.  
  39. #if !defined (SIGCHLD) && defined (SIGCLD)
  40. #define SIGCHLD SIGCLD
  41. #endif /* SIGCLD */
  42.  
  43. #include <sys/types.h>
  44.  
  45. #ifdef WINDOWSNT
  46. #define    NOMINMAX
  47. #include <windows.h>
  48. #include <fcntl.h>
  49. #include "ntsig.h"
  50. /* Defined in process.h which conflicts with the local copy */
  51. #define _P_NOWAIT 1
  52. #else /* !WINDOWSNT */
  53. #include <sys/file.h>
  54. #endif /* !WINDOWSNT */
  55.  
  56. #ifdef USG5
  57. #include <fcntl.h>
  58. #endif
  59.  
  60. #ifndef O_RDONLY
  61. #define O_RDONLY 0
  62. #endif
  63.  
  64. #ifndef O_WRONLY
  65. #define O_WRONLY 1
  66. #endif
  67.  
  68. #include "lisp.h"
  69. #include "commands.h"
  70. #include "buffer.h"
  71. #include "paths.h"
  72. #include "process.h"
  73. #include "syssignal.h"
  74.  
  75. #include "callproc_p.h"
  76. #include "xdisp_p.h"
  77. #include "sysdep_p.h"
  78. #include "alloca_p.h"
  79. #include "fileio_p.h"
  80. #include "insdel_p.h"
  81. #ifdef WINDOWSNT
  82. /* In CRT process.h which conflicts with local process.h */
  83. extern int _CRTAPI1 _getpid(void);
  84. #include <direct.h>
  85. #include "ntproc_p.h"
  86. #endif
  87. static Lisp_Object call_process_kill _P_((Lisp_Object fdpid));
  88. static Lisp_Object delete_temp_file _P_((Lisp_Object name));
  89. static int getenv_internal _P_((char *var, int varlen, char **value,
  90.                                 int *valuelen));
  91.  
  92. #ifdef VMS
  93. extern noshare char **environ;
  94. #else
  95. extern char **environ;
  96. #endif
  97.  
  98. #ifndef max
  99. #define max(a, b) ((a) > (b) ? (a) : (b))
  100. #endif
  101.  
  102. Lisp_Object Vexec_path, Vexec_directory, Vdata_directory;
  103. Lisp_Object Vconfigure_info_directory;
  104.  
  105. Lisp_Object Vshell_file_name;
  106.  
  107. Lisp_Object Vprocess_environment;
  108.  
  109. /* True iff we are about to fork off a synchronous process or if we
  110.    are waiting for it.  */
  111. int synch_process_alive;
  112.  
  113. /* Nonzero => this is a string explaining death of synchronous subprocess.  */
  114. char *synch_process_death;
  115.  
  116. /* If synch_process_death is zero,
  117.    this is exit code of synchronous subprocess.  */
  118. int synch_process_retcode;
  119.  
  120. #ifndef VMS  /* VMS version is in vmsproc.c.  */
  121.  
  122. static Lisp_Object
  123. call_process_kill (fdpid)
  124.      Lisp_Object fdpid;
  125. {
  126.   close (XFASTINT (Fcar (fdpid)));
  127.   EMACS_KILLPG (XFASTINT (Fcdr (fdpid)), SIGKILL);
  128.   synch_process_alive = 0;
  129.   return Qnil;
  130. }
  131.  
  132. Lisp_Object
  133. call_process_cleanup (fdpid)
  134.      Lisp_Object fdpid;
  135. {
  136.   register int pid = XFASTINT (Fcdr (fdpid));
  137.  
  138.   if (EMACS_KILLPG (pid, SIGINT) == 0)
  139.     {
  140.       int count = specpdl_ptr - specpdl;
  141.       record_unwind_protect (call_process_kill, fdpid);
  142.       message1 ("Waiting for process to die...(type C-g again to kill it instantly)");
  143.       immediate_quit = 1;
  144.       QUIT;
  145.       wait_for_termination (pid);
  146.       immediate_quit = 0;
  147.       specpdl_ptr = specpdl + count; /* Discard the unwind protect.  */
  148.       message1 ("Waiting for process to die...done");
  149.     }
  150.   synch_process_alive = 0;
  151.   close (XFASTINT (Fcar (fdpid)));
  152.   return Qnil;
  153. }
  154.  
  155. DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
  156.   "Call PROGRAM synchronously in separate process.\n\
  157. The program's input comes from file INFILE (nil means `/dev/null').\n\
  158. Insert output in BUFFER before point; t means current buffer;\n\
  159.  nil for BUFFER means discard it; 0 means discard and don't wait.\n\
  160. Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
  161. Remaining arguments are strings passed as command arguments to PROGRAM.\n\
  162. If BUFFER is 0, returns immediately with value nil.\n\
  163. Otherwise waits for PROGRAM to terminate\n\
  164. and returns a numeric exit status or a signal description string.\n\
  165. If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
  166.   (nargs, args)
  167.      int nargs;
  168.      register Lisp_Object *args;
  169. {
  170.   Lisp_Object infile, buffer, current_dir, display, path;
  171.   int fd[2];
  172.   int filefd;
  173. #ifdef WINDOWSNT
  174.   int pid;
  175. #else
  176.   register int pid;
  177. #endif /* !WINDOWSNT */
  178.   char buf[1024];
  179.   int count = specpdl_ptr - specpdl;
  180.   register unsigned char **new_argv
  181.     = (unsigned char **) alloca ((max (2, nargs - 2)) * sizeof (char *));
  182.   struct buffer *old = current_buffer;
  183. #if 0
  184.   int mask;
  185. #endif
  186.   CHECK_STRING (args[0], 0);
  187.  
  188.   if (nargs >= 2 && ! NILP (args[1]))
  189.     {
  190.       infile = Fexpand_file_name (args[1], current_buffer->directory);
  191.       CHECK_STRING (infile, 1);
  192.     }
  193.   else
  194.     infile = build_string (NULL_DEVICE);
  195.  
  196.   if (nargs >= 3)
  197.     {
  198.       register Lisp_Object tem;
  199.  
  200.       buffer = tem = args[2];
  201.       if (!(EQ (tem, Qnil)
  202.         || EQ (tem, Qt)
  203.         || XFASTINT (tem) == 0))
  204.     {
  205.       buffer = Fget_buffer (tem);
  206.       CHECK_BUFFER (buffer, 2);
  207.     }
  208.     }
  209.   else 
  210.     buffer = Qnil;
  211.  
  212.   /* Make sure that the child will be able to chdir to the current
  213.      buffer's current directory, or its unhandled equivalent.  We
  214.      can't just have the child check for an error when it does the
  215.      chdir, since it's in a vfork.
  216.  
  217.      We have to GCPRO around this because Fexpand_file_name,
  218.      Funhandled_file_name_directory, and Ffile_accessible_directory_p
  219.      might call a file name handling function.  The argument list is
  220.      protected by the caller, so all we really have to worry about is
  221.      buffer.  */
  222.   {
  223.     struct gcpro gcpro1, gcpro2, gcpro3;
  224.  
  225.     current_dir = current_buffer->directory;
  226.  
  227.     GCPRO3 (infile, buffer, current_dir);
  228.  
  229.     current_dir = 
  230.       expand_and_dir_to_file
  231.     (Funhandled_file_name_directory (current_dir), Qnil);
  232.     if (NILP (Ffile_accessible_directory_p (current_dir)))
  233.       report_file_error ("Setting current directory",
  234.              Fcons (current_buffer->directory, Qnil));
  235.  
  236.     UNGCPRO;
  237.   }
  238.  
  239.   display = nargs >= 4 ? args[3] : Qnil;
  240.  
  241.   {
  242.     register int i;
  243.     for (i = 4; i < nargs; i++)
  244.       {
  245.     CHECK_STRING (args[i], i);
  246.     new_argv[i - 3] = XSTRING (args[i])->data;
  247.       }
  248.     /* Program name is first command arg */
  249.     new_argv[0] = XSTRING (args[0])->data;
  250.     new_argv[i - 3] = 0;
  251.   }
  252.  
  253.   filefd = open (XSTRING (infile)->data, O_RDONLY, 0);
  254.   if (filefd < 0)
  255.     {
  256.       report_file_error ("Opening process input file", Fcons (infile, Qnil));
  257.     }
  258.   /* Search for program; barf if not found.  */
  259.   openp (Vexec_path, args[0], EXEC_SUFFIXES, &path, 1);
  260.   if (NILP (path))
  261.     {
  262.       close (filefd);
  263.       report_file_error ("Searching for program", Fcons (args[0], Qnil));
  264.     }
  265.   new_argv[0] = XSTRING (path)->data;
  266.  
  267.   if (XTYPE (buffer) == Lisp_Int)
  268.     fd[1] = open (NULL_DEVICE, O_WRONLY), fd[0] = -1;
  269.   else {
  270. #ifdef WINDOWSNT
  271.       /*
  272.        * Since NT's crt dup always creates inherited handles, we
  273.        * must be careful in setting up the pipe.  First create 
  274.        * non-inherited pipe handles, then create an inherited handle
  275.        * to the write end by dup-ing it, and then close the non-inherited
  276.        * end that was just duped.  This gives us one non-inherited handle
  277.        * on the read end and one inherited handle to the write end.  As
  278.        * the parent, we close the inherited handle to the write end after
  279.        * spawning the child.
  280.        *                                                  (voelker)
  281.        */
  282.       int childOut;
  283.  
  284.       _pipe(fd, 0, _O_NOINHERIT);
  285.       childOut = dup(fd[1]);
  286.       if (close(fd[1]) < 0) {
  287.       report_file_error("Closing parent's write end of pipe", Qnil);
  288.       }
  289.       fd[1] = childOut;
  290.  
  291. #else /* !WINDOWSNT */
  292.       pipe (fd);
  293. #endif /* !WINDOWSNT */
  294. #if 0
  295.       /* Replaced by close_process_descs */
  296.       set_exclusive_use (fd[0]);
  297. #endif
  298.     }
  299.  
  300.   {
  301.     /* child_setup must clobber environ in systems with true vfork.
  302.        Protect it from permanent change.  */
  303.     register char **save_environ = environ;
  304.     register int fd1 = fd[1];
  305.  
  306. #if 0  /* Some systems don't have sigblock.  */
  307.     mask = sigblock (sigmask (SIGCHLD));
  308. #endif
  309.  
  310.     /* Record that we're about to create a synchronous process.  */
  311.     synch_process_alive = 1;
  312.  
  313. #ifdef WINDOWSNT
  314.     child_setup (filefd, fd1, fd1, new_argv, 0, current_dir, &pid);
  315. #else /* !WINDOWSNT */
  316.     pid = vfork ();
  317.     if (pid == 0)
  318.       {
  319.     if (fd[0] >= 0)
  320.       close (fd[0]);
  321. #ifdef USG
  322.         setpgrp ();
  323. #else
  324.         setpgrp (pid, pid);
  325. #endif /* USG */
  326.     child_setup (filefd, fd1, fd1, new_argv, 0, current_dir);
  327.       }
  328. #endif /* !WINDOWSNT */
  329.  
  330.  
  331. #if 0
  332.     /* Tell SIGCHLD handler to look for this pid.  */
  333.     synch_process_pid = pid;
  334.     /* Now let SIGCHLD come through.  */
  335.     sigsetmask (mask);
  336. #endif
  337.  
  338.     environ = save_environ;
  339.  
  340.     close (filefd);
  341.     close (fd1);
  342.   }
  343.  
  344.   if (pid < 0)
  345.     {
  346.       close (fd[0]);
  347.       report_file_error ("Doing vfork", Qnil);
  348.     }
  349.  
  350.   if (XTYPE (buffer) == Lisp_Int)
  351.     {
  352. #ifndef subprocesses
  353.       /* If Emacs has been built with asynchronous subprocess support,
  354.      we don't need to do this, I think because it will then have
  355.      the facilities for handling SIGCHLD.  */
  356.       wait_without_blocking ();
  357. #endif /* subprocesses */
  358.       return Qnil;
  359.     }
  360.  
  361.   synch_process_death = 0;
  362.   synch_process_retcode = 0;
  363.  
  364.   record_unwind_protect (call_process_cleanup,
  365.              Fcons (make_number (fd[0]), make_number (pid)));
  366.  
  367.  
  368.   if (XTYPE (buffer) == Lisp_Buffer)
  369.     Fset_buffer (buffer);
  370.  
  371.   immediate_quit = 1;
  372.   QUIT;
  373.  
  374.   {
  375.     register int nread;
  376.  
  377.     while ((nread = read (fd[0], buf, sizeof buf)) > 0)
  378.       {
  379.     immediate_quit = 0;
  380.     if (!NILP (buffer))
  381.       insert (buf, nread);
  382.     if (!NILP (display) && INTERACTIVE)
  383.       redisplay_preserve_echo_area ();
  384.     immediate_quit = 1;
  385.     QUIT;
  386.       }
  387.   }
  388.  
  389.   /* Wait for it to terminate, unless it already has.  */
  390.   wait_for_termination (pid);
  391.  
  392.   immediate_quit = 0;
  393.  
  394.   set_buffer_internal (old);
  395.  
  396.   unbind_to (count, Qnil);
  397.  
  398.   if (synch_process_death)
  399.     return build_string (synch_process_death);
  400.   return make_number (synch_process_retcode);
  401. }
  402. #endif
  403.  
  404. static Lisp_Object
  405. delete_temp_file (name)
  406.      Lisp_Object name;
  407. {
  408.     if (unlink (XSTRING (name)->data) == 0)
  409.         return Qt;
  410.     else
  411.         return Qnil;
  412. }
  413.  
  414. DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
  415.   3, MANY, 0,
  416.   "Send text from START to END to a synchronous process running PROGRAM.\n\
  417. Delete the text if fourth arg DELETE is non-nil.\n\
  418. Insert output in BUFFER before point; t means current buffer;\n\
  419.  nil for BUFFER means discard it; 0 means discard and don't wait.\n\
  420. Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
  421. Remaining args are passed to PROGRAM at startup as command args.\n\
  422. If BUFFER is nil, returns immediately with value nil.\n\
  423. Otherwise waits for PROGRAM to terminate\n\
  424. and returns a numeric exit status or a signal description string.\n\
  425. If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
  426.   (nargs, args)
  427.      int nargs;
  428.      register Lisp_Object *args;
  429. {
  430.   register Lisp_Object filename_string, start, end;
  431.   char tempfile[20];
  432.   int count = specpdl_ptr - specpdl;
  433.  
  434. #ifdef VMS
  435.   strcpy (tempfile, "tmp:emacsXXXXXX.");
  436. #else
  437.   sprintf (tempfile, "%ctmp%cemacsXXXXXX", PATH_SEPARATOR, PATH_SEPARATOR);
  438. #endif
  439.   mktemp (tempfile);
  440.  
  441.   filename_string = build_string (tempfile);
  442.   start = args[0];
  443.   end = args[1];
  444.   Fwrite_region (start, end, filename_string, Qnil, Qlambda);
  445.   record_unwind_protect (delete_temp_file, filename_string);
  446.  
  447.   if (!NILP (args[3]))
  448.     Fdelete_region (start, end);
  449.  
  450.   args[3] = filename_string;
  451.  
  452.   return unbind_to (count, Fcall_process (nargs - 2, args + 2));
  453. }
  454.  
  455. #ifndef VMS /* VMS version is in vmsproc.c.  */
  456.  
  457. /* This is the last thing run in a newly forked inferior
  458.    either synchronous or asynchronous.
  459.    Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
  460.    Initialize inferior's priority, pgrp, connected dir and environment.
  461.    then exec another program based on new_argv.
  462.  
  463.    This function may change environ for the superior process.
  464.    Therefore, the superior process must save and restore the value
  465.    of environ around the vfork and the call to this function.
  466.  
  467.    ENV is the environment for the subprocess.
  468.  
  469.    SET_PGRP is nonzero if we should put the subprocess into a separate
  470.    process group.  
  471.  
  472.    CURRENT_DIR is an elisp string giving the path of the current
  473.    directory the subprocess should have.  Since we can't really signal
  474.    a decent error from within the child, this should be verified as an
  475.    executable directory by the parent.  */
  476.  
  477. _VOID_
  478. child_setup (in, out, err, new_argv, set_pgrp, current_dir
  479. #ifdef WINDOWSNT
  480.     , cpid            // yeech!
  481. #endif /* WINDOWSNT */
  482. )
  483.      int in, out, err;
  484.      register char **new_argv;
  485.      int set_pgrp;
  486.      Lisp_Object current_dir;
  487. #ifdef    WINDOWSNT
  488.     int *cpid;            // yeech!
  489. #endif /* WINDOWSNT */
  490. {
  491.   char **env;
  492.  
  493.   register int pid = getpid();
  494. #ifdef WINDOWSNT
  495.   HANDLE parent, errHandle, stdinSave, stdoutSave, stderrSave;
  496. #endif /* WINDOWSNT */
  497.  
  498. #ifndef WINDOWSNT
  499.   {
  500.     extern int emacs_priority;
  501.  
  502.     nice (- emacs_priority);
  503.   }
  504. #endif /* !WINDOWSNT */
  505.  
  506. #ifdef subprocesses
  507. #ifndef WINDOWSNT
  508.   /* Close Emacs's descriptors that this process should not have.  */
  509.   close_process_descs ();
  510. #endif /* !WINDOWSNT */
  511. #endif
  512.  
  513.   /* Note that use of alloca is always safe here.  It's obvious for systems
  514.      that do not have true vfork or that have true (stack) alloca.
  515.      If using vfork and C_ALLOCA it is safe because that changes
  516.      the superior's static variables as if the superior had done alloca
  517.      and will be cleaned up in the usual way.  */
  518.   {
  519.     register unsigned char *temp;
  520.     register int i;
  521.  
  522.     i = XSTRING (current_dir)->size;
  523.     temp = (unsigned char *) alloca (i + 2);
  524.     bcopy (XSTRING (current_dir)->data, temp, i);
  525.     if (temp[i - 1] != PATH_SEPARATOR) temp[i++] = PATH_SEPARATOR;
  526.     temp[i] = 0;
  527.  
  528.     /* We can't signal an Elisp error here; we're in a vfork.  Since
  529.        the callers check the current directory before forking, this
  530.        should only return an error if the directory's permissions
  531.        are changed between the check and this chdir, but we should
  532.        at least check.  */
  533.     if (chdir (temp) < 0)
  534.       exit (errno);
  535.   }
  536.  
  537.   /* Set `env' to a vector of the strings in Vprocess_environment.  */
  538.   {
  539.     register Lisp_Object tem;
  540.     register char **new_env;
  541.     register int new_length;
  542.  
  543.     new_length = 0;
  544.     for (tem = Vprocess_environment;
  545.      (XTYPE (tem) == Lisp_Cons
  546.       && XTYPE (XCONS (tem)->car) == Lisp_String);
  547.      tem = XCONS (tem)->cdr)
  548.       new_length++;
  549.  
  550.     /* new_length + 1 to include terminating 0.  */
  551.     env = new_env = (char **) alloca ((new_length + 1) * sizeof (char *));
  552.  
  553.     /* Copy the Vprocess_environment strings into new_env.  */
  554.     for (tem = Vprocess_environment;
  555.      (XTYPE (tem) == Lisp_Cons
  556.       && XTYPE (XCONS (tem)->car) == Lisp_String);
  557.      tem = XCONS (tem)->cdr)
  558.       {
  559.     char **ep = env;
  560.     char *string = (char *) XSTRING (XCONS (tem)->car)->data;
  561.     /* See if this string duplicates any string already in the env.
  562.        If so, don't put it in.
  563.        When an env var has multiple definitions,
  564.        we keep the definition that comes first in process-environment.  */
  565.     for (; ep != new_env; ep++)
  566.       {
  567.         char *p = *ep, *q = string;
  568.         while (1)
  569.           {
  570.         if (*q == 0)
  571.           /* The string is malformed; might as well drop it.  */
  572.           goto duplicate;
  573.         if (*q != *p)
  574.           break;
  575.         if (*q == '=')
  576.           goto duplicate;
  577.         p++, q++;
  578.           }
  579.       }
  580.     *new_env++ = string;
  581.       duplicate: ;
  582.       }
  583.     *new_env = 0;
  584.   }
  585.  
  586. #ifdef    WINDOWSNT
  587.   /*
  588.    * Assuming that in, out, and err are inherited, we make them stdin,
  589.    * stdout, and stderr of the child as follows:
  590.    *   - Save the parent's current standard handles.
  591.    *   - Set the parent's standard handles to the handles being passed in.
  592.    *     (Note that _get_osfhandle() is an io.h procedure that 
  593.    *     maps crt file descriptors to NT file handles.)
  594.    *   - Spawn the child, which inherits in, out, and err as stdin,
  595.    *     stdout, and stderr.
  596.    *   - Reset the parent's standard handles to the saved handles.
  597.    *
  598.    * We assume that the caller closes in, out, and err after calling us.
  599.    *                                                      (voelker)
  600.    */
  601.   parent = GetCurrentProcess();
  602.   if (!DuplicateHandle(parent, 
  603.                GetStdHandle(STD_INPUT_HANDLE), 
  604.                parent,
  605.                &stdinSave, 
  606.                0, 
  607.                FALSE, 
  608.                DUPLICATE_SAME_ACCESS)) {
  609.       report_file_error("Duplicating parent's input handle", Qnil);
  610.   }
  611.   if (!DuplicateHandle(parent,
  612.                GetStdHandle(STD_OUTPUT_HANDLE),
  613.                parent,
  614.                &stdoutSave,
  615.                0,
  616.                FALSE,
  617.                DUPLICATE_SAME_ACCESS)) {
  618.       report_file_error("Duplicating parent's output handle", Qnil);
  619.   }
  620.   if (!DuplicateHandle(parent,
  621.                GetStdHandle(STD_ERROR_HANDLE),
  622.                parent,
  623.                &stderrSave,
  624.                0,
  625.                FALSE,
  626.                DUPLICATE_SAME_ACCESS)) {
  627.       report_file_error("Duplicating parent's error handle", Qnil);
  628.   }
  629.   if (!SetStdHandle(STD_INPUT_HANDLE, (HANDLE) _get_osfhandle(in))) {
  630.       report_file_error("Changing stdin handle", Qnil);
  631.   }
  632.   if (!SetStdHandle(STD_OUTPUT_HANDLE, (HANDLE) _get_osfhandle(out))) {
  633.       report_file_error("Changing stdout handle", Qnil);
  634.   }
  635.  
  636.   /*
  637.    * We lose data if we use the same handle to the pipe for stdout and
  638.    * stderr, so make a duplicate.  This took a while.
  639.    */
  640.   if (out == err) {
  641.       if (!DuplicateHandle(parent,
  642.                (HANDLE) _get_osfhandle(err),
  643.                parent,
  644.                &errHandle,
  645.                0,
  646.                TRUE,
  647.                DUPLICATE_SAME_ACCESS)) {
  648.       report_file_error("Duplicating out handle to make err handle.",
  649.                             Qnil);
  650.       }
  651.   } else {
  652.       errHandle = (HANDLE) _get_osfhandle(err);
  653.   }
  654.   if (!SetStdHandle(STD_ERROR_HANDLE, errHandle)) {
  655.       report_file_error("Changing stderr handle", Qnil);
  656.   }
  657.  
  658. #else    /* !WINDOWSNT */
  659.   /* Make sure that in, out, and err are not actually already in
  660.      descriptors zero, one, or two; this could happen if Emacs is
  661.      started with its standard in, our, or error closed, as might
  662.      happen under X.  */
  663.   in = relocate_fd (in, 3);
  664.   out = relocate_fd (out, 3);
  665.   err = relocate_fd (err, 3);
  666.  
  667.   close (0);
  668.   close (1);
  669.   close (2);
  670.  
  671.   dup2 (in, 0);
  672.   dup2 (out, 1);
  673.   dup2 (err, 2);
  674.   close (in);
  675.   close (out);
  676.   close (err);
  677. #endif    /* !WINDOWSNT */
  678.  
  679. #if !defined (IRIX)
  680. #if defined (USG)
  681.   setpgrp ();            /* No arguments but equivalent in this case */
  682. #else
  683. #ifndef WINDOWSNT
  684.   setpgrp (pid, pid);
  685. #endif /* !WINDOWSNT */
  686. #endif /* USG */
  687. #endif /* IRIX */
  688.   setpgrp_of_tty (pid);
  689.  
  690. #ifdef vipc
  691.   something missing here;
  692. #endif /* vipc */
  693.  
  694. #ifdef    WINDOWSNT
  695.   /*
  696.    * Spawn the child.  (See ntproc.c:Spawnve()).
  697.    */
  698.   *cpid = spawnve (_P_NOWAIT, new_argv[0], new_argv, env);
  699.   if (*cpid == -1) {
  700.       report_file_error("Spawning child process", Qnil);
  701.   }
  702.  
  703.   /*
  704.    * Reset our handles.
  705.    */
  706.   if (!SetStdHandle(STD_INPUT_HANDLE, stdinSave)) {
  707.       report_file_error("Resetting input handle", Qnil);
  708.   }
  709.   if (!SetStdHandle(STD_OUTPUT_HANDLE, stdoutSave)) {
  710.       report_file_error("Resetting output handle", Qnil);
  711.   }
  712.   if (!SetStdHandle(STD_ERROR_HANDLE, stderrSave)) {
  713.       report_file_error("Resetting error handle", Qnil);
  714.   }
  715.   if (out == err) {
  716.       /*
  717.        * If out and err are the same handle, then we duplicated out
  718.        * and stuck it in errHandle.  Close the duplicate to clean up.
  719.        */
  720.       if (!CloseHandle(errHandle)) {
  721.       report_file_error("Closing error handle duplicated from out.", Qnil);
  722.       }
  723.   }
  724.  
  725. #else /* !WINDOWSNT */
  726.   /* execvp does not accept an environment arg so the only way
  727.      to pass this environment is to set environ.  Our caller
  728.      is responsible for restoring the ambient value of environ.  */
  729.   environ = env;
  730.   execvp (new_argv[0], new_argv);
  731.  
  732.   write (1, "Couldn't exec the program ", 26);
  733.   write (1, new_argv[0], strlen (new_argv[0]));
  734.   _exit (1);
  735. #endif /* !WINDOWSNT */
  736. }
  737.  
  738. /* Move the file descriptor FD so that its number is not less than MIN.
  739.    If the file descriptor is moved at all, the original is freed.  */
  740. int
  741. relocate_fd (fd, min)
  742.      int fd, min;
  743. {
  744.   if (fd >= min)
  745.     return fd;
  746.   else
  747.     {
  748.       int new = dup (fd);
  749.       if (new == -1)
  750.     {
  751.       char *message1 = "Error while setting up child: ";
  752.       char *message2 = "\n";
  753.       write (2, message1, strlen (message1));
  754.       write (2, sys_errlist[errno], strlen (sys_errlist[errno]));
  755.       write (2, message2, strlen (message2));
  756.       _exit (1);
  757.     }
  758.       /* Note that we hold the original FD open while we recurse,
  759.      to guarantee we'll get a new FD if we need it.  */
  760.       new = relocate_fd (new, min);
  761.       close (fd);
  762.       return new;
  763.     }
  764. }
  765.  
  766. static int
  767. getenv_internal (var, varlen, value, valuelen)
  768.      char *var;
  769.      int varlen;
  770.      char **value;
  771.      int *valuelen;
  772. {
  773.   Lisp_Object scan;
  774.  
  775.   for (scan = Vprocess_environment; CONSP (scan); scan = XCONS (scan)->cdr)
  776.     {
  777.       Lisp_Object entry = XCONS (scan)->car;
  778.  
  779.       if (XTYPE (entry) == Lisp_String
  780.       && XSTRING (entry)->size > varlen
  781.       && XSTRING (entry)->data[varlen] == '='
  782.       && ! bcmp (XSTRING (entry)->data, var, varlen))
  783.     {
  784.       *value    = (char *) XSTRING (entry)->data + (varlen + 1);
  785.       *valuelen = XSTRING (entry)->size - (varlen + 1);
  786.       return 1;
  787.     }
  788.     }
  789.  
  790.   return 0;
  791. }
  792.  
  793. DEFUN ("getenv", Fgetenv, Sgetenv, 1, 2, 0,
  794.   "Return the value of environment variable VAR, as a string.\n\
  795. VAR should be a string.  Value is nil if VAR is undefined in the environment.\n\
  796. This function consults the variable ``process-environment'' for its value.")
  797.   (var)
  798.      Lisp_Object var;
  799. {
  800.   char *value;
  801.   int valuelen;
  802.  
  803.   CHECK_STRING (var, 0);
  804.   if (getenv_internal (XSTRING (var)->data, XSTRING (var)->size,
  805.                &value, &valuelen))
  806.     return make_string (value, valuelen);
  807.   else
  808.     return Qnil;
  809. }
  810.  
  811. /* A version of getenv that consults process_environment, easily
  812.    callable from C.  */
  813. char *
  814. egetenv (var)
  815.      char *var;
  816. {
  817.   char *value;
  818.   int valuelen;
  819.  
  820.   if (getenv_internal (var, strlen (var), &value, &valuelen))
  821.     return value;
  822.   else
  823.     return 0;
  824. }
  825.  
  826. #endif /* not VMS */
  827.  
  828. _VOID_
  829. init_callproc ()
  830. {
  831.   register char * sh;
  832.   Lisp_Object tempdir;
  833.  
  834.   {
  835.     char *data_dir = egetenv ("EMACSDATA");
  836.     
  837.     Vdata_directory =
  838.       Ffile_name_as_directory
  839.     (build_string (data_dir ? data_dir : PATH_DATA));
  840.   }
  841.  
  842.   /* Check the EMACSPATH environment variable, defaulting to the
  843.      PATH_EXEC path from paths.h.  */
  844.   Vexec_path = decode_env_path ("EMACSPATH", PATH_EXEC);
  845.   Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
  846.   Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
  847.  
  848.   tempdir = Fdirectory_file_name (Vexec_directory);
  849.   if (access (XSTRING (tempdir)->data, 0) < 0)
  850.     {
  851.       printf ("Warning: arch-dependent data dir (%s) does not exist.\n",
  852.           XSTRING (Vexec_directory)->data);
  853.       sleep (2);
  854.     }
  855.  
  856.   tempdir = Fdirectory_file_name (Vdata_directory);
  857.   if (access (XSTRING (tempdir)->data, 0) < 0)
  858.     {
  859.       printf ("Warning: arch-independent data dir (%s) does not exist.\n",
  860.           XSTRING (Vdata_directory)->data);
  861.       sleep (2);
  862.     }
  863.  
  864. #ifdef VMS
  865.   Vshell_file_name = build_string ("*dcl*");
  866. #else /* !VMS */
  867.   sh = (char *) getenv ("SHELL");
  868. #ifdef    WINDOWSNT
  869.   Vshell_file_name = build_string (sh ? sh : "cmd.exe");
  870. #else    /* !WINDOWSNT */
  871.   Vshell_file_name = build_string (sh ? sh : "/bin/sh");
  872. #endif    /* !WINDOWSNT */
  873. #endif  /* !VMS */
  874. }
  875.  
  876. _VOID_
  877. set_process_environment ()
  878. {
  879.   register char **envp;
  880.  
  881.   Vprocess_environment = Qnil;
  882. #ifndef CANNOT_DUMP
  883.   if (initialized)
  884. #endif
  885.     for (envp = environ; *envp; envp++)
  886.       Vprocess_environment = Fcons (build_string (*envp),
  887.                     Vprocess_environment);
  888. }
  889.  
  890. _VOID_
  891. syms_of_callproc ()
  892. {
  893.   DEFVAR_LISP ("shell-file-name", &Vshell_file_name,
  894.     "*File name to load inferior shells from.\n\
  895. Initialized from the SHELL environment variable.");
  896.  
  897.   DEFVAR_LISP ("exec-path", &Vexec_path,
  898.     "*List of directories to search programs to run in subprocesses.\n\
  899. Each element is a string (directory name) or nil (try default directory).");
  900.  
  901.   DEFVAR_LISP ("exec-directory", &Vexec_directory,
  902.     "Directory of architecture-dependent files that come with GNU Emacs,\n\
  903. especially executable programs intended for Emacs to invoke.");
  904.  
  905.   DEFVAR_LISP ("data-directory", &Vdata_directory,
  906.     "Directory of architecture-independent files that come with GNU Emacs,\n\
  907. intended for Emacs to use.");
  908.  
  909.   DEFVAR_LISP ("configure-info-directory", &Vconfigure_info_directory,
  910.     "For internal use by the build procedure only.\n\
  911. This is the name of the directory in which the build procedure installed\n\
  912. Emacs's info files; the default value for Info-default-directory-list\n\
  913. includes this.");
  914. #ifdef WINDOWSNT
  915. {
  916.   char *infoPath = getenv("EMACSINFOPATH");
  917.   Vconfigure_info_directory = build_string (infoPath ? infoPath : PATH_INFO);
  918. }
  919. #else /* !WINDOWSNT */
  920.   Vconfigure_info_directory = build_string (PATH_INFO);
  921. #endif /* !WINDOWSNT */
  922.   DEFVAR_LISP ("process-environment", &Vprocess_environment,
  923.     "List of environment variables for subprocesses to inherit.\n\
  924. Each element should be a string of the form ENVVARNAME=VALUE.\n\
  925. The environment which Emacs inherits is placed in this variable\n\
  926. when Emacs starts.");
  927.  
  928. #ifndef VMS
  929.   defsubr (&Scall_process);
  930.   defsubr (&Sgetenv);
  931. #endif
  932.   defsubr (&Scall_process_region);
  933. }
  934.